package global

import (
	"github.com/casbin/casbin/v2"
	ut "github.com/go-playground/universal-translator"
	"go-admin/pkg/logger"
	"go-admin/pkg/setting"
	"gopkg.in/natefinch/lumberjack.v2"
	"log"
	"time"
)

var (
	ServerSetting   *setting.ServerSetting
	AppSetting      *setting.AppSetting
	DatabaseSetting *setting.DatabaseSetting
	Logger          *logger.Logger
	Trans           ut.Translator // 全局翻译器
	EmailSetting    *setting.EmailSetting
	Enforcer        *casbin.Enforcer
	MinioSetting    *setting.MinioSetting
)

// 设定配置
func SetupSetting() error {
	settingConf, err := setting.NewViper()
	if err != nil {
		return err
	}
	// 配置服务端配置
	if err = settingConf.ReadSection("Server", &ServerSetting); err != nil {
		return err
	}

	// 配置应用参数
	if err = settingConf.ReadSection("App", &AppSetting); err != nil {
		return err
	}

	// 加载数据库
	if err = settingConf.ReadSection("Database", &DatabaseSetting); err != nil {
		return err
	}

	// 加载minio
	if err = settingConf.ReadSection("Minio", &MinioSetting); err != nil {
		return err
	}

	// 设置读超时时间
	ServerSetting.ReadTimeout *= time.Second
	// 设置写超时时间
	ServerSetting.WriteTimeout *= time.Second
	// 设置项目根路径
	AppSetting.RootDir = setting.InferRootDir()

	return nil
}

func SetupEmailSetting() error {
	settingConf, err := setting.NewViper()
	if err != nil {
		return err
	}
	if err = settingConf.ReadSection("Email", &EmailSetting); err != nil {
		return err
	}
	return nil
}

func SetupLogger() error {
	Logger = logger.NewLogger(&lumberjack.Logger{
		Filename:  AppSetting.LogSavePath + "/" + AppSetting.LogFileName + AppSetting.LogFileExt,
		MaxSize:   600,
		MaxAge:    10,
		LocalTime: true,
	}, "", log.LstdFlags)
	return nil
}
